import java.util.HashMap;
import java.util.Map;
import java.util.PriorityQueue;
import java.util.Set;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 23735
 * Date: 2023-05-12
 * Time: 22:38
 */
public class Solution {
    public int[] topKFrequent(int[] nums, int k) {
        Map<Integer, Integer> map = new HashMap<>();
        for (int x: nums) {
            map.put(x, map.getOrDefault(x, 0) + 1);
        }
        Set<Map.Entry<Integer, Integer>> set = map.entrySet();
        PriorityQueue<Map.Entry<Integer, Integer>> minHeap = new PriorityQueue<>((o1, o2) -> o1.getValue() - o2.getValue());
        for (Map.Entry<Integer, Integer> entry: set) {
            if (minHeap.size() < k){
                minHeap.add(entry);
            }else{
                if (entry.getValue() > minHeap.peek().getValue()){
                    minHeap.remove();
                    minHeap.add(entry);
                }
            }
        }
        int[] result = new int[k];
        for (int i = 0;i < k;i++){
            result[i] = minHeap.poll().getKey();
        }
        return result;
    }
}
